<template>
  <div class="my-applications-container">
    <div class="applications-header">
      <div class="header-content">
        <h1>我的申请</h1>
        <p>查看您的所有职位申请状态</p>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <el-button type="primary" @click="goToSearch">
          <el-icon><Plus /></el-icon>
          申请新职位
        </el-button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon pending">
          <el-icon><Clock /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ pendingCount }}</h3>
          <p>待筛选</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon passed">
          <el-icon><Trophy /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ passedCount }}</h3>
          <p>筛选通过</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon failed">
          <el-icon><Close /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ failedCount }}</h3>
          <p>筛选未通过</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon interviewing">
          <el-icon><VideoCamera /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ interviewingCount }}</h3>
          <p>面试中</p>
        </div>
      </div>
      
      <div class="stat-card">
        <div class="stat-icon completed">
          <el-icon><Check /></el-icon>
        </div>
        <div class="stat-content">
          <h3>{{ completedCount }}</h3>
          <p>已完成</p>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="control-bar">
      <div class="filter-section">
        <el-select v-model="statusFilter" placeholder="筛选状态" clearable style="width: 150px">
          <el-option label="全部" value="" />
          <el-option label="待筛选" value="pending" />
          <el-option label="筛选通过" value="screened_pass" />
          <el-option label="筛选未通过" value="screened_fail" />
          <el-option label="面试中" value="interviewing" />
          <el-option label="已完成" value="completed" />
        </el-select>
      </div>
      
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索公司或职位..."
          prefix-icon="Search"
          @input="handleSearch"
          style="width: 300px"
        />
      </div>
    </div>

    <!-- 申请列表 -->
    <div v-if="loading" class="loading-section">
      <el-skeleton :rows="5" animated v-for="n in 3" :key="n" />
    </div>
    
    <div v-else-if="filteredApplications.length > 0" class="applications-list">
      <div v-for="application in filteredApplications" :key="application.id" class="application-card">
        <div class="card-header">
          <div class="job-info">
            <div class="company-logo">
              <span>{{ application.company.charAt(0) }}</span>
            </div>
            <div class="job-details">
              <h4>{{ application.job_title }}</h4>
              <p>{{ application.company }}</p>
            </div>
          </div>
          <div class="application-status">
            <el-tag :type="getStatusTagType(application.status)">
              {{ getStatusText(application.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="card-content">
          <div class="application-details">
            <div class="detail-item">
              <el-icon><Calendar /></el-icon>
              <span>申请时间：{{ formatDateTime(application.applied_at) }}</span>
            </div>
            <div class="detail-item" v-if="application.match_score">
              <el-icon><TrendCharts /></el-icon>
              <span>匹配度：{{ application.match_score }}%</span>
              <span class="required-score">(要求：{{ application.required_match_score }}%)</span>
            </div>
            <div class="detail-item" v-if="application.resume_file_name">
              <el-icon><Document /></el-icon>
              <span>简历：{{ application.resume_file_name }}</span>
            </div>
          </div>
          
          <!-- 技能匹配信息 -->
          <div v-if="application.core_skills_matched?.length > 0" class="skills-section">
            <h5>核心技能匹配</h5>
            <div class="skills-tags">
              <el-tag v-for="skill in application.core_skills_matched" :key="skill" type="success" size="small">
                {{ skill }}
              </el-tag>
            </div>
          </div>
          
          <div v-if="application.soft_skills_detected?.length > 0" class="skills-section">
            <h5>软技能检测</h5>
            <div class="skills-tags">
              <el-tag v-for="skill in application.soft_skills_detected" :key="skill" type="primary" size="small">
                {{ skill }}
              </el-tag>
            </div>
          </div>
          
          <!-- 简历亮点 -->
          <div v-if="application.highlights?.length > 0" class="highlights-section">
            <h5>简历亮点</h5>
            <ul class="highlights-list">
              <li v-for="highlight in application.highlights" :key="highlight">
                {{ highlight }}
              </li>
            </ul>
          </div>
        </div>
        
        <div class="card-footer">
          <div class="application-actions">
            <el-button 
              v-if="application.status === 'screened_pass'"
              type="primary" 
              size="small"
              @click="startInterview(application)"
            >
              开始面试
            </el-button>
            <el-button 
              v-if="application.status === 'screened_fail'"
              type="warning" 
              size="small"
              @click="viewFeedback(application)"
            >
              查看反馈
            </el-button>
            <el-button 
              v-if="application.status === 'completed'"
              type="info" 
              size="small"
              @click="viewResult(application)"
            >
              查看结果
            </el-button>
            <el-button 
              size="small"
              @click="viewJobDetail(application)"
            >
              查看职位
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <div v-else class="empty-state">
      <el-empty description="暂无申请记录">
        <el-button type="primary" @click="goToSearch">去申请职位</el-button>
      </el-empty>
    </div>

    <!-- 反馈对话框 -->
    <el-dialog
      v-model="feedbackDialogVisible"
      title="筛选反馈"
      width="600px"
    >
      <div v-if="selectedApplication && selectedApplication.screening_feedback" class="feedback-content">
        <div v-for="item in selectedApplication.screening_feedback" :key="item.dimension" class="feedback-item">
          <div class="feedback-header">
            <span class="dimension">{{ item.dimension }}</span>
            <span class="score">{{ item.score }}/{{ item.max_score }}</span>
          </div>
          <div class="feedback-comment">{{ item.comments }}</div>
          <el-progress 
            :percentage="(item.score / item.max_score) * 100" 
            :color="getScoreColor((item.score / item.max_score) * 100)"
            :stroke-width="6"
          />
        </div>
        
        <div v-if="selectedApplication.screening_suggestions?.length > 0" class="suggestions-section">
          <h4>改进建议</h4>
          <ul class="suggestions-list">
            <li v-for="suggestion in selectedApplication.screening_suggestions" :key="suggestion">
              {{ suggestion }}
            </li>
          </ul>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { candidateApi } from '@/services/api'
import { 
  ArrowLeft, 
  Plus,
  Clock,
  Trophy,
  Close,
  VideoCamera,
  Check,
  Calendar,
  TrendCharts,
  Document
} from '@element-plus/icons-vue'

export default {
  name: 'MyInterviewsView',
  components: {
    ArrowLeft,
    Plus,
    Clock,
    Trophy,
    Close,
    VideoCamera,
    Check,
    Calendar,
    TrendCharts,
    Document
  },
  setup() {
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(true)
    const applications = ref([])
    const searchQuery = ref('')
    const statusFilter = ref('')
    const feedbackDialogVisible = ref(false)
    const selectedApplication = ref(null)
    
    // 计算属性
    const pendingCount = computed(() => 
      applications.value.filter(app => app.status === 'pending').length
    )
    
    const passedCount = computed(() => 
      applications.value.filter(app => app.status === 'screened_pass').length
    )
    
    const failedCount = computed(() => 
      applications.value.filter(app => app.status === 'screened_fail').length
    )
    
    const interviewingCount = computed(() => 
      applications.value.filter(app => app.status === 'interviewing').length
    )
    
    const completedCount = computed(() => 
      applications.value.filter(app => app.status === 'completed').length
    )
    
    const filteredApplications = computed(() => {
      let filtered = applications.value
      
      // 状态筛选
      if (statusFilter.value) {
        filtered = filtered.filter(app => app.status === statusFilter.value)
      }
      
      // 搜索筛选
      if (searchQuery.value) {
        const query = searchQuery.value.toLowerCase()
        filtered = filtered.filter(app => 
          app.job_title.toLowerCase().includes(query) ||
          app.company.toLowerCase().includes(query)
        )
      }
      
      return filtered
    })
    
    // 方法
    const goBack = () => {
      router.go(-1)
    }
    
    const goToSearch = () => {
      router.push('/candidate/search-interviews')
    }
    
    const handleSearch = () => {
      // 搜索逻辑已在计算属性中处理
    }
    
    const getStatusTagType = (status) => {
      const typeMap = {
        'pending': 'warning',
        'screened_pass': 'success',
        'screened_fail': 'danger',
        'interviewing': 'primary',
        'completed': 'info'
      }
      return typeMap[status] || 'info'
    }
    
    const getStatusText = (status) => {
      const textMap = {
        'pending': '待筛选',
        'screened_pass': '筛选通过',
        'screened_fail': '筛选未通过',
        'interviewing': '面试中',
        'completed': '已完成'
      }
      return textMap[status] || '未知状态'
    }
    
    const formatDateTime = (dateString) => {
      if (!dateString) return '-'
      return new Date(dateString).toLocaleString('zh-CN')
    }
    
    const getScoreColor = (percentage) => {
      if (percentage >= 80) return '#67c23a'
      if (percentage >= 60) return '#e6a23c'
      return '#f56c6c'
    }
    
    const startInterview = (application) => {
      router.push(`/candidate/interview-session/${application.id}`)
    }
    
    const viewFeedback = (application) => {
      selectedApplication.value = application
      feedbackDialogVisible.value = true
    }
    
    const viewResult = (application) => {
      router.push(`/candidate/interview-result?applicationId=${application.id}`)
    }
    
    const viewJobDetail = (application) => {
      router.push(`/candidate/job-detail/${application.job_id}`)
    }
    
    // 加载申请数据
    const loadApplications = async () => {
      loading.value = true
      try {
        const response = await candidateApi.getMyApplications()
        console.log('我的申请数据:', response)
        
        if (response.results) {
          applications.value = response.results
        } else if (Array.isArray(response)) {
          applications.value = response
        } else {
          applications.value = []
        }
      } catch (error) {
        console.error('加载申请数据失败:', error)
        ElMessage.error('加载申请数据失败')
        
        // 使用模拟数据
        applications.value = [
          {
            id: 1,
            job_title: '前端开发工程师',
            job_id: 1,
            company: '腾讯科技',
            match_score: 85.5,
            required_match_score: 70.0,
            status: 'screened_pass',
            applied_at: '2024-01-16T10:00:00Z',
            resume_file_name: '张三简历.pdf',
            core_skills_matched: ['JavaScript', 'Vue.js', 'React'],
            soft_skills_detected: ['沟通能力', '团队合作'],
            highlights: ['3年前端开发经验', '熟悉现代前端框架'],
            screening_feedback: [],
            screening_suggestions: []
          },
          {
            id: 2,
            job_title: '全栈开发工程师',
            job_id: 2,
            company: '阿里巴巴',
            match_score: 62.0,
            required_match_score: 75.0,
            status: 'screened_fail',
            applied_at: '2024-01-15T14:30:00Z',
            resume_file_name: '张三简历.pdf',
            core_skills_matched: ['JavaScript', 'Node.js'],
            soft_skills_detected: ['学习能力'],
            highlights: ['有学习能力'],
            screening_feedback: [
              {
                dimension: '硬技能匹配度',
                score: 25.0,
                max_score: 40.0,
                comments: '缺少核心技能: Python, Django'
              }
            ],
            screening_suggestions: [
              '补充相关技术栈的项目经验',
              '在简历中明确体现软技能案例'
            ]
          }
        ]
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      loadApplications()
    })
    
    return {
      loading,
      applications,
      searchQuery,
      statusFilter,
      feedbackDialogVisible,
      selectedApplication,
      pendingCount,
      passedCount,
      failedCount,
      interviewingCount,
      completedCount,
      filteredApplications,
      goBack,
      goToSearch,
      handleSearch,
      getStatusTagType,
      getStatusText,
      formatDateTime,
      getScoreColor,
      startInterview,
      viewFeedback,
      viewResult,
      viewJobDetail
    }
  }
}
</script>

<style scoped>
.my-applications-container {
  padding: 2rem;
  max-width: 1200px;
  margin: 0 auto;
}

.applications-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 2rem;
}

.header-content h1 {
  font-size: 2rem;
  font-weight: 600;
  color: #303133;
  margin: 0 0 0.5rem 0;
}

.header-content p {
  color: #606266;
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.stat-card {
  background: white;
  padding: 1.5rem;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 1rem;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.stat-icon.pending {
  background: #e6a23c;
}

.stat-icon.passed {
  background: #67c23a;
}

.stat-icon.failed {
  background: #f56c6c;
}

.stat-icon.interviewing {
  background: #409eff;
}

.stat-icon.completed {
  background: #909399;
}

.stat-content h3 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.stat-content p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.control-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding: 1rem;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.loading-section {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.applications-list {
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.application-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.2s, box-shadow 0.2s;
}

.application-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #e4e7ed;
}

.job-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.company-logo {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  background: #409eff;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 18px;
}

.job-details h4 {
  font-size: 1.1rem;
  font-weight: 600;
  color: #303133;
  margin: 0 0 4px 0;
}

.job-details p {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.card-content {
  padding: 1.5rem;
}

.application-details {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
  margin-bottom: 1rem;
}

.detail-item {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #606266;
  font-size: 14px;
}

.required-score {
  color: #909399;
  font-size: 12px;
  margin-left: 4px;
}

.skills-section {
  margin-bottom: 1rem;
}

.skills-section h5 {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.skills-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.highlights-section {
  margin-bottom: 1rem;
}

.highlights-section h5 {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.highlights-list {
  margin: 0;
  padding-left: 20px;
}

.highlights-list li {
  color: #606266;
  font-size: 14px;
  margin-bottom: 4px;
}

.card-footer {
  padding: 1rem 1.5rem;
  background: #f5f7fa;
  border-top: 1px solid #e4e7ed;
}

.application-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.empty-state {
  text-align: center;
  padding: 3rem;
}

/* 反馈对话框样式 */
.feedback-content {
  max-height: 60vh;
  overflow-y: auto;
}

.feedback-item {
  margin-bottom: 20px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.feedback-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.dimension {
  font-weight: 600;
  color: #303133;
}

.score {
  color: #409eff;
  font-weight: 600;
}

.feedback-comment {
  color: #606266;
  font-size: 14px;
  margin-bottom: 12px;
  line-height: 1.5;
}

.suggestions-section {
  margin-top: 20px;
}

.suggestions-section h4 {
  margin: 0 0 12px 0;
  color: #303133;
  font-size: 16px;
}

.suggestions-list {
  margin: 0;
  padding-left: 20px;
}

.suggestions-list li {
  margin-bottom: 8px;
  color: #606266;
  line-height: 1.5;
}

@media (max-width: 768px) {
  .my-applications-container {
    padding: 1rem;
  }
  
  .applications-header {
    flex-direction: column;
    gap: 1rem;
  }
  
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .control-bar {
    flex-direction: column;
    gap: 1rem;
    align-items: stretch;
  }
  
  .application-actions {
    flex-direction: column;
  }
}
</style> 